<route lang="json5" type="page">
{
	style: {
		navigationStyle: 'custom',
		navigationBarTitleText: '图书详情',
	},
}
</route>

<template>
	<view class="page-book-details">
		<fly-navbar backgroundColor="transparent" textColor="#ffffff" leftText="图书详情" fixed />
		<image
			class="w-full h-full fixed top-0 left-0 z-1"
			:src="baseImg + '/class-top-bg.png'"
		></image>
		<scroll-view
			scroll-y
			class="w-full h-[100vh] absolute top-0 left-0 z-2 box-border"
			:style="{ paddingTop: barAlbright + 'rpx' }"
			v-if="thisPage === 1"
		>
			<view class="w-full py-6 box-border">
				<view class="w-full px-[34rpx] box-border">
					<view
						class="w-full px-[35rpx] py-[31rpx] box-border rounded-[31rpx] bg-white book-details-info"
					>
						<view class="w-full flex justify-between items-center">
							<image
								:src="detailsInfo.cover_img"
								class="w-[243rpx] h-[286rpx] rounded-[25rpx]"
							></image>
							<view
								class="flex-1 pt-3 pb-2 pl-2 flex flex-col justify-between h-[286rpx] box-border"
							>
								<view class="w-full flex flex-col">
									<text class="text-[#303030] text-[36rpx]">{{ detailsInfo.name }}</text>
									<text class="text-[#919191] text-[24rpx]" v-if="detailsInfo.author">{{
										detailsInfo.author
									}}</text>
								</view>
								<view class="w-full flex flex-col justify-end">
									<text class="text-[#919191] text-[24rpx] inline-block"
										>出版社: {{ detailsInfo.publisher || '-' }}</text
									>
									<text class="text-[#919191] text-[24rpx] inline-block"
										>阅读对象: {{ detailsInfo.grade_name || '-' }}</text
									>
									<view
										class="mt-[22rpx] relative px-4 h-[38rpx] flex justify-center text-[#fff] text-[21rpx] items-center border-1 border-solid border-[#F1F1F1] rounded-[17rpx]"
										style="width: fit-content; background: #2ba5e0"
									>
										<view
											class="flex items-center mr-2"
											v-if="detailsInfo.finish_book_user_avatar.length"
										>
											<image
												class="w-[47rpx] h-[47rpx] -ml-[30rpx] border-1 border-solid border-[#fff] rounded-[50%]"
												v-for="item in detailsInfo.finish_book_user_avatar"
												:key="item"
												:src="item.avatar || baseImg + '/user-default.png'"
											></image>
										</view>
										{{ detailsInfo.finish_book_user_count }}
										人读过</view
									>
								</view>
							</view>
						</view>
						<view class="w-full flex justify-between items-center mt-[31rpx]">
							<view
								class="px-[44rpx] py-[18rpx] rounded-[35rpx] flex justify-center items-center"
								@tap="toSelf"
								style="background-color: #f0f1f3"
							>
								<image
									v-if="detailsInfo.is_bookself === 0"
									class="w-[33rpx] h-[33rpx]"
									:src="baseImg + '/book/book-add-icon.jpg'"
								></image>
								<image
									v-else
									class="w-[33rpx] h-[33rpx]"
									:src="baseImg + '/book/book-success-icon.jpg'"
								></image>
								<text class="text-[#303030] text-[29rpx] ml-[10rpx]">加入书架</text>
							</view>
							<view
								class="px-[44rpx] py-[18rpx] rounded-[35rpx] flex justify-center items-center"
								@tap="toResource"
								style="background-color: #f0f1f3"
							>
								<image
									class="w-[36rpx] h-[29rpx]"
									:src="baseImg + '/book/book-resource-icon.png'"
								></image>
								<text class="text-[#303030] text-[29rpx] ml-[10rpx]">图书拓展资源</text>
							</view>
						</view>
					</view>
				</view>
                <view class="newBanner  w-full"  @tap="downPDF(detailsInfo.answer_url)" v-if="detailsInfo.answer_url">
					<image :src="baseImg + '/newBanner.jpg'" mode="widthFix"  class="newBannerImg rounded-[35rpx]"></image>
				</view>
				<view
					class="w-full px-[34rpx] paper-bg box-border relative pt-[74rpx]"
					v-if="detailsInfo.book_paper.length"
				>
					<view
						class="w-full relative"
						v-for="(pithed, index) in detailsInfo.book_paper"
						:key="pithed.id"
						:id="'item-' + pithed.id"
						:style="{
							background: `url(${baseImg + '/book/book-pass-' + ((index % 3) + 1) + '.jpg'}) no-repeat`,
							backgroundSize: '100% 100%',
							borderRadius:
								index === 0
									? '40rpx 40rpx 0 0'
									: index === detailsInfo.book_paper.length - 1
										? '0 0 40rpx 40rpx'
										: '',
						}"
					>
						<view
							class="w-full box-border px-[40rpx]"
							:style="{
								paddingBottom: '40rpx',
								paddingTop: index === 0 ? '104rpx' : '0',
							}"
						>
							<view
								:class="[
									'w-full h-[87rpx] px-[53rpx] box-border flex items-center absolute -top-[43rpx] left-0',
									detailsInfo.plan_progress === 100 ? 'justify-between' : 'justify-center',
								]"
								v-if="index === 0"
							>
								<view class="w-[272rpx] h-[87rpx] relative">
									<image class="w-full h-full" :src="baseImg + '/book/book-paper-icon.png'">
									</image>
									<view
										class="absolute right-[30rpx] w-[56rpx] h-[28rpx] top-[25rpx] flex justify-center items-center text-[#fff] text-[22rpx]"
										>{{ (detailsInfo.plan_progress || 0) + '%' }}</view
									>
								</view>
								<view
									class="w-[272rpx] h-[87rpx] relative"
									v-if="detailsInfo.plan_progress === 100 && detailsInfo.book_integral === 0"
									:style="{
										background: `url(${baseImg + '/book/book-pass-finish.png'}) no-repeat`,
										backgroundSize: '100%',
									}"
									@tap="receive"
								>
									<view class="w-full h-full flex px-[29rpx] box-border justify-end items-center">
										<view class="flex items-center text-[25rpx] text-[#fff] mb-[11rpx]">
											+{{ detailsInfo.single_book_integral || 0 }}
											<image
												class="w-[34rpx] h-[34rpx] ml-[10rpx]"
												:src="baseImg + '/book/book-pass-point.png'"
											></image> </view
									></view>
								</view>
								<view
									class="w-[272rpx] h-[87rpx] relative"
									v-if="detailsInfo.plan_progress === 100 && detailsInfo.book_integral > 0"
									:style="{
										background: `url(${baseImg + '/book/book-pass-unfinish.png'}) no-repeat`,
										backgroundSize: '100%',
									}"
								>
									<view class="w-full h-full flex px-[29rpx] box-border justify-end items-center">
										<view class="flex items-center text-[25rpx] text-[#fff]">
											+{{ detailsInfo.single_book_integral || 0 }}
											<image
												class="w-[34rpx] h-[34rpx] ml-[10rpx]"
												:src="baseImg + '/book/book-pass-point.png'"
											></image> </view
									></view>
								</view>
							</view>

							<view class="w-full flex justify-center items-center flex-col relative box-border">
								<block
									v-if="
										pithed.answer_id ||
										detailsInfo.book_paper.findIndex(cited => cited.id === pithed.id) === 0 ||
										detailsInfo.book_paper[
											detailsInfo.book_paper.findIndex(cited => cited.id === pithed.id) - 1
										]?.star_number >= pithed.unlock_star_number
									"
								>
									<view
										@tap="toPaper(pithed)"
										class="w-[193rpx] h-[83rpx] flex justify-center items-center z-2"
										:style="{
											background: `url(${baseImg + '/book/book-test.png'}) no-repeat`,
											backgroundSize: '100%',
										}"
									>
										<text class="paper-text">第{{ index + 1 }}站</text>
									</view>
									<view
										@tap="toPaper(pithed)"
										class="w-full flex -mt-[40rpx] min-h-[255rpx] px-4 justify-center items-center flex-col rounded-[31rpx] pt-[76rpx] pb-[31rpx] box-border read-item"
									>
										<text class="text-[#303030] text-[26rpx]">{{ pithed.name }}</text>
										<rich-text
											class="text-[#5E5E5E] text-[22rpx] mt-[27rpx]"
											:nodes="pithed.descript"
										></rich-text>
										<view class="flex justify-center items-center mt-[32rpx]">
											<image
												class="w-[42rpx] h-[42rpx] mr-[5rpx] last:mr-0"
												v-for="(cited, windex) in [1, 2, 3]"
												:key="cited"
												:src="
													pithed.star_number > windex
														? baseImg + '/book/book-star.png'
														: baseImg + '/book/book-star-gray.png'
												"
											></image>
										</view>
									</view>
								</block>
								<block v-else>
									<view
										class="w-[193rpx] h-[83rpx] flex justify-center items-center z-2"
										:style="{
											background: `url(${baseImg + '/book/book-lock.png'}) no-repeat`,
											backgroundSize: '100%',
										}"
									>
									</view>
									<view
										class="w-full flex -mt-[40rpx] min-h-[255rpx] justify-center items-center flex-col rounded-[31rpx] px-4 pt-[76rpx] pb-[31rpx] box-border read-item"
										style="background: #f8f8f8"
									>
										<text class="text-[26rpx]" style="color: rgb(48 48 48 / 50%)"
											>前一站达到{{ pithed.unlock_star_number }}星后解锁</text
										>

										<view class="flex justify-center items-center mt-[32rpx]">
											<image
												class="w-[42rpx] h-[42rpx] mr-[5rpx] last:mr-0"
												v-for="cited in [1, 2, 3]"
												:key="cited"
												:src="baseImg + '/book/book-star-gray.png'"
											></image>
										</view>
									</view>
								</block>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="w-full h-[100vh] absolute top-0 left-0 z-2 box-border" v-if="thisPage === 0">
			<no-page :btnTitle="btnTitle" :type="type" :title="title" @click="retry"></no-page>
		</view>
		<view class="zhezhao" v-if="thisLogin === 0" @click="retry"></view>
	</view>
</template>

<script lang="ts" setup>
import { systemInfo } from '@/utils/getSystemInfo';
import { storeToRefs } from 'pinia';
import { toAuthPage } from '@/utils/jump';
import { initializeApp } from '@/utils/index';
import { useUserStore } from '@/store';
import { getReceivePoint } from '@/service/user';
import { getBookDetails, getBookDetailsNoLogin, setBookSelf, getBookResourceClass } from '@/service/book';
import onShare from '@/hooks/useShare';

const baseImg = ref(import.meta.env.VITE_STATIC_IMAGE);
const { statusBarHeight, navHeight } = systemInfo();
const userStore = useUserStore();
const barAlbright = ref(0);
const { userInfo } = storeToRefs(userStore);
const detailsInfo = ref(null);
const title = ref('');
const type = ref('btn');
const thisPage = ref(-1);
const thisLogin = ref(-1);
const query = ref(null);
const btnTitle = ref('重试');
const resourceClass = ref([]);

onLoad(options => {
	// id: 图书id
	// plan_id: 计划id
	//console.log(options)
	 console.log('userInfo.value.student_id',userInfo.value.student_id)
	if (!userInfo.value.student_id) {
		// 分享或者进入未登录
		 thisPage.value = 1;
		 thisLogin.value = 0;
		// type.value = 'btn';
		// title.value = '还没有登录';
		// btnTitle.value = '登录';
		// uni.hideShareMenu({ hideShareItems: ['qq', 'qzone'] });
		// return;
	} else {
		thisLogin.value = 1;
	}
	
	if (options) {
		if (options.scene) {
			query.value = {id : options.scene};
		} else {
			query.value = options;
		}
	} else {
		thisPage.value = 0;
		type.value = 'msg';
		title.value = '并未查询到该书籍,请返回重试';
	}
});

onShow(() => {
	barAlbright.value = navHeight + statusBarHeight;
	console.log('thisLogin.value',getDetailsInfoNOLogin);
	if (query.value?.id) {
		if(thisLogin.value == 0) {
			initializeApp(getDetailsInfoNOLogin(query.value.id));
		} else {
			initializeApp(getDetailsInfo(query.value.id), getResourceClass(query.value.id));
		}
	}
});

const getResourceClass = async (id: number) => {
	const res = await getBookResourceClass({
		book_id: Number(id),
	});
	resourceClass.value = res.data;
};


const getDetailsInfoNOLogin = async (id: number) => {
	  // uni.showToast({
	  // 	title: '您还未登录，请登录继续访问',
	  // 	duration: 3000,
	  // 	icon:'none'
	  // });
	try {
		const res = await getBookDetailsNoLogin({
			book_id: Number(id),
		});
		// uni.hideLoading();
		if (res.status_code === 200 && res.data) {
			thisPage.value = 1;
			detailsInfo.value = res.data;
			setTimeout(() => {
				uni.showToast({
					title: '您还未登录，请登录继续访问',
					duration: 30000,
					icon:'none'
				});
			},500)
		} else {
			// uni.showToast({
			// 	title: '您还未登录，请登录继续访问',
			// 	duration: 30000,
			// 	icon:'none'
			// });
		}
	} catch (error) {
		// uni.hideLoading();
		// uni.showToast({
		// 	title: '您还未登录，请登录继续访问',
		// 	duration: 30000,
		// 	icon:'none'
		// });
	}
};

const getDetailsInfo = async (id: number) => {
	try {
		const res = await getBookDetails({
			book_id: Number(id),
			student_id: userInfo.value.student_id,
		});
		// uni.hideLoading();
		if (res.status_code === 200 && res.data) {
			thisPage.value = 1;
			detailsInfo.value = res.data;
		} else {
			thisPage.value = 0;
			title.value = res.message;
		}
	} catch (error) {
		// uni.hideLoading();
		thisPage.value = 0;
		title.value = '服务器异常';
	}
};

const retry = () => {
	if (!userInfo.value.student_id) {
		// 分享或者进入未登录
		toAuthPage({}, { type: 'redirectTo', url: '/pages/index/index' });
		return;
	}
	getDetailsInfo(query.value.id);
};

const toPaper = item => {
	let url = '';
	if (item.answer_id) {
		url = `/pages-book/exercise/details/index?answer_id=${item.answer_id}${query.value.plan_id ? `&plan_id=${query.value.plan_id}` : ''}`;
	} else {
		url = `/pages-book/exercise/index?id=${
			item.id
		}${query.value.plan_id ? `&plan_id=${query.value.plan_id}` : ''}`;
	}
	uni.navigateTo({
		url,
	});
};

const toResource = () => {
	if (!resourceClass.value.length) {
		uni.showToast({
			icon: 'none',
			title: '暂无相关拓展资源',
		});
		return;
	}
	uni.navigateTo({
		url: `/pages-book/resource/index?id=${query.value.id}`,
	});
};

const toSelf = async () => {
	if (!userInfo.value.student_id) {
		toAuthPage();
	} else {
		if (detailsInfo.value.is_bookself === 1) {
			uni.showToast({ icon: 'none', title: '该书目已在书架中' });
			return;
		}
		uni.showLoading({ title: '加入中...' });
		try {
			const res = await setBookSelf({
				book_id: Number(query.value.id),
				student_id: userInfo.value.student_id,
			});
			uni.hideLoading();
			if (res.status_code === 200) {
				uni.showToast({
					icon: 'none',
					title: '添加成功',
				});
				retry();
			}
		} catch (error) {
			uni.hideLoading();
		}
	}
};




const receive = async () => {
	uni.showLoading({
		title: '领取中...',
	});
	try {
		const res = await getReceivePoint({
			student_id: userInfo.value.student_id,
			book_id: query.value.id || 0,
			plan_id: query.value.plan_id || 0,
		});
		uni.hideLoading();
		if (res.status_code === 200) {
			uni.showToast({
				icon: 'none',
				title: '领取成功',
				success: () => {
					retry();
				},
			});
		} else {
			uni.showToast({
				icon: 'none',
				title: res.message,
			});
		}
	} catch (error) {
		uni.hideLoading();
		uni.showToast({
			icon: 'none',
			title: '领取失败,请重试',
		});
	}
};

 function whatFileType(file_url:String){
	const index= file_url.lastIndexOf(".");
	return file_url.substr(index+1);
}


const downPDF = (url:String) => {
	uni.showLoading({title: '加载中'});
	console.log(url);
	wx.downloadFile({
	  url:url,
	  success: function (res) {
	    var filePath = res.tempFilePath;
		// console.log(filePath);
		console.log(whatFileType(filePath))
		// uni.hideLoading();
	    wx.openDocument({
	      filePath: filePath,
		  fileType: whatFileType(filePath),
	      success: function (res) {
	        console.log('打开文档成功');
	      },
		  fail:function(res) {
		  	 console.log(res);
		  }
	    });
	  },
	  fail:function(res) {
		  console.log(res);
	  }
	});
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { onShareAppMessage, onShareTimeline } = onShare();
</script>

<style lang="scss">
page {
	background-color: #62c7f2;
}
</style>
<style lang="scss" scoped>
.zhezhao {
  position: fixed;
  left: 0;
  right: 0;
  width: 100vw;
  height: 160vh;
  top:0;
  z-index: 9;
}
.newBanner {
	overflow: hidden;
	padding-left: 34rpx;
	padding-right: 34rpx;
	box-sizing: border-box;
	padding-top: 34rpx;
	
	.newBannerImg {
		width: 100%;
		height:160rpx;
		box-shadow:
			0rpx 0rpx 3rpx 0rpx rgb(0 0 0 / 3%),
			0rpx 5rpx 21rpx 0rpx rgb(0 0 0 / 7%);
	}

}
.page-book-details {
	background-color: #62c7f2;

	.book-details-info {
		box-shadow:
			0rpx 0rpx 3rpx 0rpx rgb(0 0 0 / 3%),
			0rpx 5rpx 21rpx 0rpx rgb(0 0 0 / 7%);
	}

	.read-item {
		background: #fff6e2;
		box-shadow:
			0rpx 0rpx 3rpx 0rpx rgb(0 0 0 / 3%),
			0rpx 5rpx 21rpx 0rpx rgb(0 0 0 / 7%);
	}

	.paper-text {
		font-size: 35rpx;
		color: #f3f5f0;
		text-shadow:
			#5ea015 1px 0 0,
			#5ea015 0 1px 0,
			#5ea015 -1px 0 0,
			#5ea015 0 -1px 0;
	}

	.book-dui {
		width: 4rpx;
		height: 8rpx;
		border-color: #303030;
		border-style: solid;
		border-width: 0 4rpx 4rpx 0;
		transform: rotate(45deg);
	}
}
</style>
